package toubiao.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javassist.compiler.ast.NewExpr;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mysql.jdbc.log.Log;

import toubiao.dao.business.ContractDaoI;
import toubiao.dao.business.ProjectDaoI;
import toubiao.domain.excel.ProjectGrid4Excel;
import toubiao.domain.po.business.PoContract;
import toubiao.domain.po.business.PoProject;
import toubiao.domain.po.manage.PoResource;
import toubiao.domain.vo.assist.Json;
import toubiao.domain.vo.assist.PageHelper;
import toubiao.domain.vo.business.ContractGrid;
import toubiao.domain.vo.business.ProjectDetail;
import toubiao.domain.vo.business.ProjectGrid;
import toubiao.domain.vo.easyUi.DataGrid;
import toubiao.exception.CustomException;
import toubiao.utils.Dictionary;
import toubiao.utils.ProConstant;
import toubiao.utils.ProUtilConfig;
import toubiao.utils.ProUtilExcel;
import toubiao.utils.ProUtilPoConvert;
import toubiao.utils.ProUtilVoConvert;
import toubiao.utils.excel.domain.ExcelModel;
import toubiao.utils.filter.Convert;
import toubiao.utils.filter.FilterCondition;
import toubiao.utils.filter.HqlBuilder;
import toubiao.utils.filter.OrderCondition;
import toubiao.utils.old.ProUtilPoExcelConvert;
import toubiao.utils.old.ProUtilPoVoConvert;
import utils.UtilCollection;
import utils.UtilJackson;
import utils.UtilString;
import utils.UtilUuid;
import utils.easyui.UtilEzDatagrid;
import utils.easyui.domain.EzDatagrid;

@Service
public class ProjectServiceImpl {
	
	private Logger logger=LoggerFactory.getLogger(ProjectServiceImpl.class);

	@Autowired
	private ProjectDaoI projectDao;
	
	@Autowired
	private ContractDaoI contractDao;
	
	@Autowired
	private ProUtilVoConvert proUtilVoConvert;
	
	
	public  DataGrid getDataGridByConditions(List<FilterCondition> filterConditionList, List<OrderCondition> orderConditionList,PageHelper ph) {
		String listBaseHql=Dictionary.HQL_MAP.get("projectGridList");
		String countBaseHql=Dictionary.HQL_MAP.get("projectGridCount");
		Convert convert=Dictionary.HQL_COMMON_CONVERT;
		
		DataGrid dg = new DataGrid();
		
		String listHql=HqlBuilder.buildHql(listBaseHql, convert, filterConditionList, orderConditionList);
		String countHql=HqlBuilder.buildHql(countBaseHql, convert, filterConditionList, orderConditionList);
		
		logger.info(listHql);
		logger.info(countHql);
		
		List<PoProject> list=projectDao.find(listHql, ph.getPage(), ph.getRows());
		List<PoProject> listCount=projectDao.find(countHql);
		
		List<ProjectGrid> gridList=ProUtilPoVoConvert.getVoListOfProjectGrid(list);
		
		dg.setRows(gridList);
		dg.setTotal(Long.valueOf(listCount.size()));
		String jsonString=UtilJackson.me().object2Json(dg);
		logger.info(jsonString);
		
		return dg;
	}
	
	public List<PoProject> getPoProjectByIds(String ids) throws CustomException {
		List<PoProject> projectList=new ArrayList<>();
		String[] idArray=ids.split(",");
		if(idArray==null || idArray.length==0){
			throw new CustomException("ids is error");
		}
		for(String id:idArray){
			PoProject poProject=projectDao.get(PoProject.class, Long.parseLong(id));
			projectList.add(poProject);
		}
		return projectList;
	}
	
	public List<PoProject> getPoProjectAll() {
		String listBaseHql=Dictionary.HQL_MAP.get("projectGridList");
		List<PoProject> projectList=projectDao.find(listBaseHql);
		return projectList;
	}
	
	public List<PoProject> getPoProjectByCondition(List<FilterCondition> filterConditionList, List<OrderCondition> orderConditionList){
		String listBaseHql=Dictionary.HQL_MAP.get("projectGridList");
		Convert convert=Dictionary.HQL_COMMON_CONVERT;
		String listHql=HqlBuilder.buildHql(listBaseHql, convert, filterConditionList, orderConditionList);
		logger.info(listHql);
		List<PoProject> list=projectDao.find(listHql);
		return list;
	}
	
	public String creatProjectGridExcelFile(List<PoProject> list) throws IOException{
		List<ProjectGrid4Excel> excProjectGridList=ProUtilPoExcelConvert.getExcelProjectGridList(list);
		String fileAbsPath=ProUtilConfig.getDownloadTempPath()+"/"+UtilUuid.getUuidString()+".xlsx";
		ExcelModel excelModel=Dictionary.EXCEL_MODEL_MAP.get("projectGrid");
		ProUtilExcel.list2ExcelFile(fileAbsPath, excProjectGridList, excelModel);
		return fileAbsPath;
	}
	
	public void forTest(){
		String hql="select distinct project from PoProject project left join fetch project.contractSet contract left join fetch project.partA left join fetch project.snList sn";
		List<PoProject>list =projectDao.find(hql);
		logger.info(list.size()+"");
	}

	public String downloadFileCheckedByIds(String fileType,String ids) throws CustomException, IOException {	
		List<PoProject> poProjectList=getPoProjectByIds(ids);
		if(fileType.trim().equalsIgnoreCase("excel")){
			return creatProjectGridExcelFile(poProjectList);
		}
		
		throw new CustomException("FileType must be excel or docx.");
	}
	
	public String downloadFileAll(String fileType) throws CustomException, IOException {	
		List<PoProject> poProjectList=getPoProjectAll();
		if(fileType.trim().equalsIgnoreCase("excel")){
			return creatProjectGridExcelFile(poProjectList);
		}
		
		throw new CustomException("FileType must be excel or docx.");
	}
	
	public String downloadFileByConditions(String fileType,List<FilterCondition> filterConditionList, List<OrderCondition> orderConditionList) throws CustomException, IOException {	
		List<PoProject> poProjectList=getPoProjectByCondition(filterConditionList, orderConditionList);
		if(fileType.trim().equalsIgnoreCase("excel")){
			return creatProjectGridExcelFile(poProjectList);
		}
		
		throw new CustomException("FileType must be excel or docx.");
	}

	public String downloadeExcelChecked(String ids) {
		// TODO Auto-generated method stub
		return null;
	}

	public Json getProjectDetail(String projectId) {
		// TODO Auto-generated method stub
		Json json=new Json();
		if(projectId==null){
			json.setMessage("projectId is null.");
			return json;
		}
		
		Long id=null;;
		try {
			id=Long.parseLong(projectId);
		} catch (NumberFormatException e) {
			// TODO: handle exception
			e.printStackTrace();
			json.setMessage("projectId 格式错误，能转换为数字");
		}
		
		PoProject poProject=projectDao.get(PoProject.class, id);
		if(poProject==null){
			json.setMessage("无此 id 数据 ");
		}
		ProjectDetail projectDetail=null;
		try {
			projectDetail=ProUtilPoConvert.convertRoute(PoProject.class, ProjectDetail.class, poProject);
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			json.setMessage("服务内部转换错误，projectDetail");
		}
		json.setData(projectDetail);
		json.setSuccess(true);
		
		return json;
	}

	public Json updateProjectDetail(ProjectDetail projectDetail) {
		// TODO Auto-generated method stub
		Json json=new Json();
		if(projectDetail==null || projectDetail.getId()==null){
			json.setMessage("detail is null or id is null.");
			return json;
		}
		Long id=projectDetail.getId();
		PoProject project=projectDao.get(PoProject.class, id);
		project=proUtilVoConvert.getProject(projectDetail, project);
		projectDao.update(project);
		json.setData(projectDetail);
		json.setSuccess(true);
		json.setMessage("update is ok.");
		
		return json;
	}
	
	public EzDatagrid<ContractGrid> getContractDataGridByProjectId(String projectId ) throws CustomException, InstantiationException, IllegalAccessException {
		if(UtilString.isNullOrEmpty(projectId)){
			throw new CustomException("projectId is null or ''");
		}
		PoProject poProject=projectDao.get(PoProject.class,Long.parseLong(projectId));
		if(poProject==null){
			throw new CustomException("不能找到 projectId = "+projectId +" PoProje对象");
		}
		Set<PoContract> contractSet=poProject.getContractSet();
		logger.info(contractSet.size()+"");
		List<ContractGrid> contractGridList=ProUtilPoConvert.getList(PoContract.class, ContractGrid.class, contractSet);
		logger.info(contractGridList.size()+"");
		EzDatagrid<ContractGrid> datagrid=UtilEzDatagrid.getDataGridByCollection(contractGridList);
		return datagrid;
	}

	public Json updateLinkWithContract(String projectId, String contractIds) {
		Json json=new Json();
		
		if(UtilString.isNullOrEmpty(projectId) || contractIds==null){
			json.setMessage("参数 错误.");
			return json;
		}
		
		PoProject project=projectDao.get(PoProject.class, Long.parseLong(projectId));
		List<PoContract> contractList=contractDao.getListByIds(PoContract.class, contractIds, ",");
		
		Set<PoContract> contractSet=new HashSet<>();
		contractSet.addAll(contractList);
		
		project.setContractSet(contractSet);
		
		projectDao.update(project);
		json.setSuccess(true);
		return json;
	}
	
}
